package com.itheima.socket.udp.demo02;

import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * 发送数据端：
 * 键盘录入数据，将数据发送到接收端
 */
public class SendDemo01 {

    public static void main(String[] args) throws Exception {

        // 1. 创建DatagramSocket对象
        DatagramSocket datagramSocket = new DatagramSocket() ;

        // 2. 使用循环不断的接收键盘录入的数据，将数据发送到接收端
        while(true) {

            // 2.1 创建Scanner对象 , 接收键盘录入数据
            Scanner scanner = new Scanner(System.in) ;
            String sendDataInfo = scanner.next();

            // 2.2 创建DatagramPacket对象，封装要发送的数据： public DatagramPacket(byte buf[], int length,InetAddress address, int port)
            byte[] bytes = sendDataInfo.getBytes("UTF-8");
            int length = bytes.length;
            InetAddress inetAddress = InetAddress.getByName("169.254.106.206");// 也可以去使用127.0.0.1
            int port = 9999 ;
            DatagramPacket datagramPacket = new DatagramPacket(bytes , length , inetAddress , port) ;

            // 2.3 调用datagramSocket对象的方法去发送数据
            datagramSocket.send(datagramPacket);

        }

    }

}
